import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../../shared/smartadmin.config'
import { C } from '@angular/core/src/render3'
declare var XLSX: any
declare var $: any
@Component({
  selector: 'sa-binding-user',
  templateUrl: './binding-user.component.html'
})
export class BindingUserManageComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableParam: any = {
    phone: '',
    name: '',
    // searchKey: '',
    isFollow: '0',
    appletsCode: ''
  }
  phoneList: any = []
  nameList: any = []
  isShowAdd: boolean = false
  isShowDel: boolean = false
  filePhoneUp: string = ''
  fileCarUp: string = ''
  upload_phone: File = null //导入手机号码文件的回调参数
  upload_car: File = null //导入车辆文件的回调参数
  title: string = ''
  preViewData = []
  carSelectData: any = {
    userId: '',
    carNumber: '',
    deviceId: '',
    companyName: '',
    companyId: ''
  }

  bindCarForm: any = {
    phone: '',
    carNumber: ''
  }

  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      phoneNumber: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请输入手机号码'
          }
        }
      }
    }
  }
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  ngOnInit() {
    this.initBtn()
    this.load()
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initPhone()
      })
    })
  }
  //初始化权限按钮
  initBtn() {
    var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_appletsManage:bindingUser')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'bindingUser:addBtn' && item.parentId) {
        this.isShowAdd = true
      }
      if (item.sourceKey === 'bindingUser:delBtn' && item.parentId) {
        this.isShowDel = true
      }
    }
  }

  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        isFollow: this.tableParam.isFollow,
        phone: this.tableParam.phone,
        name: this.tableParam.name,
        appletsCode: this.tableParam.appletsCode
        // searchKey:common.stringTrim(this.tableParam.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('appointmentRepairCar/appointmentUserList.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //初始化车辆
  initPhone() {
    var that = this
    $('#phoneSelect2')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 2,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'appointmentRepairCar/findQueryParam.html',
          dataType: 'json',
          delay: 100,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              param: params.term,
              type: 1
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, car) {
              options.push({
                id: car.id,
                text: car.phone
              })
            })
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.phone = data.text
      })
    $('#nameSelect2')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 2,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'appointmentRepairCar/findQueryParam.html',
          dataType: 'json',
          delay: 100,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              param: params.term,
              type: 2
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, car) {
              options.push({
                id: car.id,
                text: car.name
              })
            })
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.name = data.text
      })
  }

  detailRow(row) {
    console.log(row)
    const BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('carDetail', JSON.stringify(row))
    window.open(BaseURL + '#/wx-bind/applets-manage/car-authentication')
  }

  delPhone() {
    this.tableParam.phone = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#phoneSelect2').val('')
    $('#select2-phoneSelect2-container').empty()
    $('#select2-phoneSelect2-container').attr('title', '')
    $('#select2-phoneSelect2-container').prepend(str)
  }
  delName() {
    this.tableParam.name = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#nameSelect2').val('')
    $('#select2-nameSelect2-container').empty()
    $('#select2-nameSelect2-container').attr('title', '')
    $('#select2-nameSelect2-container').prepend(str)
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  /**
   *
   * 查看车牌
   */

  phone: any = '' //请求列表数据
  appletsCode: any = '' //请求列表数据
  carOpenid: any = '' //请求列表数据
  carId: any = '' //请求列表数据
  viewCarData: any = [] //车牌数据列表
  carNumberSubList: any = [] //请求的车辆数据
  //查看车辆列表
  viewRow(row, modal) {
    this.appletsCode = row.appletsCode
    this.phone = row.phone
    this.carOpenid = row.carId
    this.carSelectData.userId = row.id

    this.requestCarList()
    modal.show()
  }

  //请求车辆列表
  requestCarList() {
    var reqdata = {
      appletsCode: this.appletsCode ? this.appletsCode : '0001',
      phone: this.phone
    }
    this.jsonApiService
      .http_obj('appointmentRepairCar/findBandingCarRecordListByOpenid.html', reqdata)
      .subscribe(data => {
        if (data.success) {
          this.viewCarData = data.data
        } else {
          this.jsonApiService.message(data.message)
        }
      })
  }
  closeViewCarModal(modal) {
    modal.hide()
  }
  //初始化车辆
  initCar() {
    var that = this
    // $('#patchSelect2')
    //   .select2({
    //     language: 'zh-CN',
    //     placeholder: '请选择',
    //     allowClear: true,
    //     minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
    //     ajax: {
    //       url: config.BaseURL + 'stats/carListByCarNumber.html',
    //       dataType: 'json',
    //       delay: 50,
    //       method: 'POST',
    //       xhrFields: { withCredentials: true },
    //       data: function (params) {
    //         return { carNumber: params.term }
    //       },
    //       processResults: function (data, params) {
    //         var options = new Array()
    //         // 小于10个数量才判断重复
    //         if (data.data.length <= 10) {
    //           let arr = []
    //           let sameCar = []
    //           // 判断相同的车牌号
    //           for (let index = 0; index < data.data.length; index++) {
    //             let car = data.data[index]
    //             if (arr.indexOf(car.carNumber) != -1) {
    //               sameCar.push(car.carNumber)
    //             } else {
    //               arr.push(car.carNumber)
    //             }
    //           }
    //           $(data.data).each(function (index, car) {
    //             if (sameCar.indexOf(car.carNumber) != -1) {
    //               options.push({
    //                 id: car.id,
    //                 text: car.carNumber + '[' + car.parentName + ']',
    //                 deviceId: car.deviceId,
    //                 carNumber: car.carNumber
    //               })
    //             } else {
    //               options.push({
    //                 id: car.id,
    //                 text: car.carNumber,
    //                 deviceId: car.deviceId,
    //                 carNumber: car.carNumber
    //               })
    //             }
    //           })
    //         } else {
    //           $(data.data).each(function (index, car) {
    //             options.push({
    //               id: car.id,
    //               text: car.carNumber,
    //               deviceId: car.deviceId,
    //               carNumber: car.carNumber
    //             })
    //           })
    //         }
    //         return {
    //           results: options //获取查询后的结果
    //         }
    //       },
    //       cache: true
    //     },
    //     templateResult: this.formatRepo
    //   })
    //   .on('select2:select', function (e) {
    //     var data = e.params.data
    //     $('#carNumberInput').val(data.text).change()
    //     var obj = {
    //       carNumber: data.carNumber,
    //       deviceId: data.deviceId,
    //       carId: data.id
    //     }
    //     for (let i = 0, len = that.carNumberSubList.length; i < len; i++) {
    //       if (that.carNumberSubList[i].carId === data.id) {
    //         return
    //       }
    //     }
    //     that.carNumberSubList.push(obj)
    //   })
    //   .on('select2:unselect', function (e) {
    //     var data = e.params.data
    //     for (let i = 0, len = that.carNumberSubList.length; i < len; i++) {
    //       if (that.carNumberSubList[i].carId === data.id) {
    //         that.carNumberSubList.splice(i, 1)
    //         break
    //       }
    //     }
    //   })
    $('#patchSelect2')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 4,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'repairOrder/findCarInfoByCarNumber.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return { carNumber: params.term.replace(/\s*/g, ''), type: 2 }
          },
          processResults: function (data, params) {
            var options = new Array()
            var resultCarNumber = data.data.dockingInfo || []
            // 小于10个数量才判断重复
            if (resultCarNumber.length <= 10) {
              let arr = []
              let sameCar = []
              // 判断相同的车牌号
              for (let index = 0; index < resultCarNumber.length; index++) {
                let car = resultCarNumber[index]
                if (arr.indexOf(car.carNumber) != -1) {
                  sameCar.push(car.carNumber)
                } else {
                  arr.push(car.carNumber)
                }
              }
              $(resultCarNumber).each(function (index, car) {
                if (sameCar.indexOf(car.carNumber) != -1) {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber + '[' + car.dockingFactoryName + ']' + '[' + car.deviceId + ']',
                    dockingFactoryName: car.dockingFactoryName,
                    dockingFactoryId: car.dockingFactoryId
                  })
                } else {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber,
                    dockingFactoryName: car.dockingFactoryName,
                    dockingFactoryId: car.dockingFactoryId
                  })
                }
              })
            } else {
              $(resultCarNumber).each(function (index, car) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber,
                  dockingFactoryName: car.dockingFactoryName,
                  dockingFactoryId: car.dockingFactoryId
                })
              })
            }
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.carSelectData.deviceId = data.id
        that.carSelectData.companyName = data.dockingFactoryName
        that.carSelectData.companyId = data.dockingFactoryId
        if (data.text.indexOf('[') > 0) {
          that.carSelectData.carNumber = data.text.split('[')[0]
        } else {
          that.carSelectData.carNumber = data.text
        }
      })
  }

  //擦除用户所选值
  delCarNumberSelect() {
    this.carSelectData.deviceId = ''
    this.carSelectData.carNumber = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#patchSelect2').val('')
    $('#select2-patchSelect2-container').empty()
    $('#select2-patchSelect2-container').attr('title', '')
    $('#select2-patchSelect2-container').prepend(str)
  }

  //添加车辆
  addViewCar(modal) {
    var that = this
    modal.show()
    that.carNumberSubList = []
    setTimeout(function () {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          that.initCar()
          $('#carNumberInput').val('').change()
          that.clearSelect2($('#patchSelect2')) //清除Select中的数据
        })
      })
    }, 100)
  }
  //清空select2
  clearSelect2(obj) {
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }
  //删除车辆
  deleteViewCar(row) {
    var toastText
    if (row.selected == 1) {
      if (this.viewCarData.length == 1) {
        toastText = '用户当前绑定该车,删除后用户无绑定车辆,确认要删除?'
      } else {
        toastText = '用户当前绑定该车,删除后会自动为用户绑定时间最新的车,确认要删除?'
      }
    } else {
      toastText = '此操作将永久删除数据,确认要删除?'
    }
    this.jsonApiService.confirm_message(toastText).then(() => {
      let parameters = {
        id: row.id,
        userId: this.carSelectData.userId
      }
      this.jsonApiService.http_obj('appointmentRepairCar/deleteBandingCarRecord.html', parameters).subscribe(data => {
        this.jsonApiService.message(data.message)
        this.requestCarList()
      })
    })
  }

  //关闭
  viewCarClose(modal) {
    modal.hide()
  }
  //提交
  viewCarSubmit(modal) {
    console.log(this.carSelectData)
    if (!this.carSelectData.carNumber) {
      this.jsonApiService.message('请先添加车牌号码')
      return
    }
    var reqdata = {
      ...this.carSelectData
    }

    this.jsonApiService.http_obj('appointmentRepairCar/addBandingRecord.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.requestCarList()
        modal.hide()
      }
    })
  }

  exportByBindCar(modal) {
    modal.show()
    $('#bindCarForm').data('bootstrapValidator').resetForm()
    this.bindCarForm = {
      phone: '',
      carNumber: ''
    }
  }

  closeCarModal(modal) {
    modal.hide()
    // $('#bindCarForm').data('bootstrapValidator').resetForm()
  }

  /* 是否手机号码或者固话*/
  validatePhoneTwo(value) {
    const reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/
    return reg.test(value)
  }
  /* 是否车牌号*/
  validateCarNum(value) {
    const reg =
      /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
    return reg.test(value)
  }

  handleConfirm(modal) {
    // 手机号码必填项改为选填项
    // $('#bindCarForm').bootstrapValidator('validate') //开启验证
    // let isValid = $('#bindCarForm').data('bootstrapValidator').isValid() //验证是否通过
    // if (!isValid) return
    // const param = {
    //   phone:[],
    //   carNumber:[]
    // }
    // const phoneArray = this.bindCarForm.phone.split(",")
    // phoneArray.forEach(item=>{
    //   const bol = this.validatePhoneTwo(item)
    //   if(bol){
    //     param.phone.push(item.trim())
    //   }
    // })

    // const carNumberArray = this.bindCarForm.carNumber.split(",")
    // if(carNumberArray.length>0){
    //   carNumberArray.forEach(item=>{
    //     param.carNumber.push(item.trim())
    //   })
    // }

    const param = {
      phone: this.bindCarForm.phone ? this.bindCarForm.phone.split(',') : [],
      carNumber: this.bindCarForm.carNumber ? this.bindCarForm.carNumber.split(',') : []
    }
    // if(param.phone.length>0){
    const Url = 'appointmentRepairCar/exportBindingCarRecords.html'
    common.exprotDataFile(param, 'param', config.BaseURL + Url)
    modal.hide()
    $('#bindCarForm').data('bootstrapValidator').resetForm()
    // }else{
    //   this.jsonApiService.message('手机号码格式有误,请检查！')
    // }
  }

  // 下载模板
  download_template(url, fileName) {
    const fileUrl = config.BaseURL + url
    fetch(fileUrl)
      .then(res => res.blob())
      .then(blob => {
        const downloadElement = document.createElement('a')
        downloadElement.href = URL.createObjectURL(blob)
        // 下载文件的名称及文件类型后缀
        downloadElement.download = fileName
        document.body.appendChild(downloadElement)
        downloadElement.click()
        //在资源下载完成后 清除 占用的缓存资源
        window.URL.revokeObjectURL(downloadElement.href)
        document.body.removeChild(downloadElement)
      })
  }

  clearFile() {
    this.fileCarUp = ''
    this.filePhoneUp = ''
  }
  //文件上传change回调
  async fileChange(files: FileList, type) {
    this.upload_phone = files.item(0)
    console.log('upload_phone', files.item(0))
    const isEXCEL =
      this.upload_phone.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.upload_phone.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.upload_phone = null
      return
    } else {
      const data = await this.readFile(files.item(0))
      const workbook = XLSX.read(data, { type: 'binary', cellDates: false }) //解析二进制格式数据
      const outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
      console.log('XLSX', workbook)
      // phoneNumber.value = []
      const numArr = []
      let headerTitle = '',
        fn: any = undefined,
        errorNumber: Array<string | number> = []
      if (type === 'phone') {
        headerTitle = '手机号码'
        fn = this.validatePhoneTwo
      } else if (type === 'car') {
        headerTitle = '绑定车辆'
        fn = this.validateCarNum
      }

      outData.map((v: any) => {
        if (v[headerTitle] && fn(v[headerTitle])) {
          numArr.push(v[headerTitle] + '')
        } else {
          errorNumber.push(v[headerTitle])
        }
      })
      if (numArr.length > 0) {
        if (type === 'phone') {
          this.bindCarForm.phone = numArr.join(',')
          if (this.bindCarForm.phone) {
            $('#bindCarForm').data('bootstrapValidator').resetField('phoneNumber')
          }
          if (errorNumber.length > 0) {
            this.jsonApiService.message('发现错误手机号码：' + errorNumber.join(','))
          }
        }
        if (type === 'car') {
          this.bindCarForm.carNumber = numArr.join(',')
          if (errorNumber.length > 0) {
            this.jsonApiService.message('发现错误车牌号码：' + errorNumber.join(','))
          }
        }
      } else {
        this.jsonApiService.message('无法从导入的文件获取到数据，请检查导入文件')
      }
    }
  }

  readFile(file) {
    //文件读取
    return new Promise(resolve => {
      let reader = new FileReader()
      reader.readAsBinaryString(file) //以二进制的方式读取
      reader.onload = ev => {
        resolve(ev.target.result)
      }
    })
  }

  preView(type: string, modal) {
    if (type === 'car') {
      modal.show()
      this.preViewData = this.bindCarForm.carNumber.split(',')
      this.title = '车牌号码'
    }

    if (type === 'phone') {
      modal.show()
      this.preViewData = this.bindCarForm.phone.split(',')
      this.title = '手机号码'
    }
  }

  handlePreView(modal) {
    modal.hide()
  }
}
